/*
 * client.c
 *
 *  Created on: Feb 12, 2012
 *      Author: jiabin
 */

#include "splitter.h"
#include "secure_rw.h"
#include <stdio.h>
#include <time.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include "auth.h"
#include <netinet/in.h>
#include <arpa/inet.h>

#define PACKET_SIZE 128

static void error(const char *s)
{
	perror(s);
	exit(1);
}

extern int sockfd;

void sighandler(int i);

int client_main(int portno, const char *ip)
{
	signal(SIGINT, &sighandler);
	srand(time(0));

	int n;
	struct sockaddr_in serv_addr;
	//struct hostent *server;

	char buffer[PACKET_SIZE];

	struct connection conn;
	conn.seq = 1;
	//conn.secret = (unsigned char *) "abcdefghijklmnop";
	//conn.iv = (unsigned char *) "0123456789abcdef";

	sockfd = conn.sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if (conn.sockfd < 0)
		error("ERROR opening socket");
	//server = gethostbyname("localhost");
//	if (server == NULL)
//	{
//		fprintf(stderr, "ERROR, no such host\n");
//		exit(0);
//	}
	bzero((char *) &serv_addr, sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
//	bcopy((char *) server->h_addr, (char *) &serv_addr.sin_addr.s_addr,
//			server->h_length);

	inet_aton(ip, &serv_addr.sin_addr);

	serv_addr.sin_port = htons(portno);
	if (connect(conn.sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
		error("ERROR connecting");

	if (auth_active(&conn, "client_cert.pem", "client_key.pem", "Splitter") < 0)
		return -1;

	while(1)
	{
		bzero(buffer, PACKET_SIZE);
		int c = read(0, buffer, PACKET_SIZE);
		n = sc_write(&conn, buffer, c);
		if (n < 0)
			error("ERROR writing to socket");
		usleep(500 * 1000);
	}

	close(conn.sockfd);
	return 0;
}
